//
//  ActivationCard.m
//  VivaModa
//
//  Created by Sergey on 2/28/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "ActivationCard.h"
#import "activation_card_cell.h"


@interface ActivationCard (){
    Boolean keyboardIsShowing;
    CGRect keyboardBounds;
    NSArray *array_step;
    UITextField *test_textField;
}

@end

@implementation ActivationCard
@synthesize categ_1;
@synthesize categ_2;
@synthesize categ_3;
@synthesize number_card;
@synthesize fio;
@synthesize telephone;
@synthesize email;
@synthesize button_send;

@synthesize Categ;
@synthesize FillField;
@synthesize infoData;
@synthesize tableView;
int current_category;


NSString *text_number_card;
NSString *text_names;
NSString *text_tel;
NSString *text_email;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self resetImageCategory];
    current_category = 0;
    [self setCategoryImage];
}



-(void)enterContentContacts{
    NSString* txt1 = @"* - поля, обязательные для заполнения";
    NSMutableAttributedString* attrStr1 = [NSMutableAttributedString attributedStringWithString:txt1];
    [attrStr1 setFont:[UIFont systemFontOfSize:14]];
    [attrStr1 setTextColor:[UIColor blackColor]];
    NSRange range = [txt1 rangeOfString:@"*"];
    [attrStr1 setTextColor:[UIColor redColor] range:range];
    FillField.attributedText = attrStr1;
    
    NSString* txt5 = @"* Категория карты:";
    NSMutableAttributedString* attrStr5 = [NSMutableAttributedString attributedStringWithString:txt5];
    [attrStr5 setFont:[UIFont systemFontOfSize:16]];
    [attrStr5 setTextColor:[UIColor blackColor]];
    [attrStr5 setTextColor:[UIColor redColor] range:range];
    Categ.attributedText = attrStr5;
    
    
    [FillField setBackgroundColor:[UIColor clearColor]];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNavigationTitle];
    [self addCustomBackButton];
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    
    [self.button_send setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.button_send setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
    
    [self.navigationItem setTitle:@"Активация"];
    
    array_step = @[
    @{@"name_step":@"* Номер карты",@"id":@"11"},
    @{@"name_step":@"* Имя, Фамилия",@"id":@"12"},
    @{@"name_step":@"* Телефон",@"id":@"13"},
    @{@"name_step":@"  e-mail",@"id":@"14"}
    ];

    [self enterContentContacts];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)resetImageCategory{
    categ_1.image = [UIImage imageNamed:@"un_checked_btn"];
    categ_2.image = [UIImage imageNamed:@"un_checked_btn"];
    categ_3.image = [UIImage imageNamed:@"un_checked_btn"];
}

-(IBAction)selectCategory:(id)sender{
    [self resetImageCategory];
    current_category = [sender tag];
    [self setCategoryImage];
}


-(void)setCategoryImage{
    switch (current_category) {
        case 1:{
            categ_1.image = [UIImage imageNamed:@"checked_btn"];
            break;}
        case 2:{
            categ_2.image = [UIImage imageNamed:@"checked_btn"];
             break;}
        case 3:{
            categ_3.image = [UIImage imageNamed:@"checked_btn"];
            break;}
        default:
            break;
    }

}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array_step count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"register_cell";
    
    
    
    activation_card_cell *cell = nil;
    cell = (activation_card_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"activation_card_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[activation_card_cell class]])
            {
                cell = (activation_card_cell *)currentObject;
                break;
            }
        }
    }
    
    int id_cell = [[[array_step objectAtIndex:indexPath.row] objectForKey:@"id"] integerValue];
    
    //NSLog(@"tag = %i",id_cell);
    
    switch (id_cell) {
        case 11:{
            cell.text_field.text = text_number_card;
            break;}
        case 12:{
            cell.text_field.text = text_names;
            break;}
        case 13:{
            cell.text_field.text = text_tel;
            break;}
        case 14:{
            cell.text_field.text = text_email;
            break;}
        default:
            break;
    }
    
    
    NSString* name_step = [[array_step objectAtIndex:indexPath.row] objectForKey:@"name_step"];
    NSRange range = [name_step rangeOfString:@"*"];
    NSMutableAttributedString* attrStr2 = [NSMutableAttributedString attributedStringWithString:name_step];
    [attrStr2 setFont:[UIFont systemFontOfSize:14]];
    [attrStr2 setTextColor:[UIColor blackColor]];
    [attrStr2 setTextColor:[UIColor redColor] range:range];
    cell.name_steps.attributedText = attrStr2;
    
    
    //cell.name_steps.text = [[array_step objectAtIndex:indexPath.row] objectForKey:@"name_step"];
    cell.text_field.tag = id_cell;
    cell.text_field.delegate = self;
    
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}



#pragma mark -
#pragma mark Keyboard Handling

- (void)keyboardWillShow:(NSNotification *)notification {
	NSDictionary *userInfo = [notification userInfo];
	[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
	keyboardIsShowing = YES;
	[self resizeViewControllerToFitScreen];
}

- (void)keyboardWillHide:(NSNotification *)note {
	keyboardIsShowing = NO;
	keyboardBounds = CGRectMake(0, 0, 0, 0);
	[self resizeViewControllerToFitScreen];
}


- (void)resizeViewControllerToFitScreen {
	// Needs adjustment for portrait orientation!
	CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
	CGRect frame = self.tableView.frame;
	frame.size.height = applicationFrame.size.height - self.tabBarController.tabBar.frame.size.height - self.navigationController.navigationBar.frame.size.height;
    
	if (keyboardIsShowing)
		frame.size.height -= (keyboardBounds.size.height-50);
    
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:0.3f];
	self.view.frame = frame;
	[UIView commitAnimations];
}




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    int id_cell = textField.tag;
    NSString *text;
    if (range.length<1) {
        
        text = [NSString stringWithFormat:@"%@%@",textField.text,string];
    }else{
        text = [textField.text substringToIndex:[textField.text length] - 1];
        //text = [NSString stringWithFormat:@"%@",textField.text];
    }
    
    switch (id_cell) {
        case 11:{
            text_number_card = text;
            break;}
        case 12:{
            text_names = text;
            break;}
        case 13:{
            text_tel = text;
            break;}
        case 14:{
            text_email = text;
            break;}
        default:
            break;
    }
    
    return YES;
}

-(void) textFieldDidBeginEditing:(UITextField *)textField {
    
    test_textField = textField;
    
    CGPoint pnt = [self.tableView convertPoint:textField.bounds.origin fromView:textField];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:pnt];
    
    [self performSelector:@selector(aaaap:) withObject:path afterDelay:0.1];
}

-(void)aaaap:(NSIndexPath*)path{
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
    [test_textField resignFirstResponder];
}


-(IBAction)pressSendData:(id)sender{
    UITextField *field_card = (UITextField *)[self.tableView viewWithTag:11];
    UITextField *field_names = (UITextField *)[self.tableView viewWithTag:12];
    UITextField *field_tel = (UITextField *)[self.tableView viewWithTag:13];
    UITextField *field_email = (UITextField *)[self.tableView viewWithTag:14];
    
    
   // NSLog(@"%@",text_number_card);
   // NSLog(@"%@",field_names.text);
   // NSLog(@"%@",field_tel.text);
   // NSLog(@"%@",field_email.text);
   // NSLog(@"%@",field_card.text);
    
    if ([text_number_card length]<1 || [text_names length]<2 || [text_tel length]<3 || [text_email length]<1 || current_category<1) {
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка ввода" message:[NSString stringWithFormat:@"Заполнены не все обязательные поля. Проверте правильность заполнения данных и повторите попытку"]];
        [alert setCancelButtonWithTitle:@"              Закрыть            " block:^{
                    }];
        [alert show];
    }else{
        NSString *type=@"";
        if (current_category==1) {
            type = @"Ёлки";
        }else{
            if (current_category==2) {
                type = @"Шишкин";
            }else{
                type = @"VIVA";
            }
        }
        
        //NSLog(@"current_category = %i",current_category);
        //NSLog(@"name card = %@",text_number_card);
        //NSLog(@"name user = %@",text_names);
        //NSLog(@"telephone = %@",text_tel);
        //NSLog(@"email = %@",text_email);
        
        
        
        NSString* params = [NSString stringWithFormat:@"cardnumber=%@&type=%@&phone=%@&name=%@&mail=%@",text_number_card,type,text_tel,text_names,text_email]; // задаем параметры POST запроса
        
        NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/activate_card.php"]; // куда отправлять
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
        
        NSURLConnection *connect = [NSURLConnection connectionWithRequest:request delegate:self];
        [self displayActivityView];
        if (connect) {
            self.infoData = [NSMutableData data];
        }

        
        
        
    }
    
}






- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
        [infoData appendData:data];
    
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
      [self parseJSON:infoData];
    
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data {
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    NSString * message = [json objectForKey:@"message"];

    
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:message];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
    }];
    [alert show];
        
    [self removeActivityView];
    
}


- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}

#pragma mark Dejal activity

- (void)displayActivityView
{
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark

-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}




-(void)setNavigationTitle{
    UILabel *lblTitle = [[UILabel alloc] init];
    lblTitle.text = @" Активация карт";
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1];
    
    lblTitle.font = [UIFont fontWithName:@"American Retro" size:27.0];
    [lblTitle sizeToFit];
    
    self.navigationItem.titleView = lblTitle;
}



-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 71, 29)];
    //[backButton setImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Инфо" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
